/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project.jpdftools.managers;

import com.itextpdf.text.pdf.PdfReader;
import java.io.File;
import java.util.logging.Level;
import project.jpdftools.toolkit.Toolkit;

/**
 *
 * @author Mido
 */
public class PDFManager {

    /**
     * Checks whether the current file is of type pdf
     *
     * @param filePath path of the file to be checked
     * @return
     */
    public static boolean isPdf(String filePath) {
        if (filePath.toLowerCase().endsWith(".pdf") == true) {
            return true;
        }
        return false;
    }

    /**
     * Get the size of the pdf files in B, KB, MB, GB or TB
     *
     * @param filePath
     * @return
     */
    public static String getFileSizeFormatted(String filePath) {
        if (isPdf(filePath) == false) {
            return "";
        }

        long fileSize = new File(filePath).length();
        if (fileSize <= 0) {
            return "0";
        }

        int unit = 1024;
        if (fileSize < unit) {
            return fileSize + " B";
        }
        int exp = (int) (Math.log(fileSize) / Math.log(unit));
        String pre = "kMGTPE".charAt(exp - 1) + "";
        return String.format("%.2f %sB", fileSize / Math.pow(unit, exp), pre);
    }

    /**
     * Get the number of pages in a pdf file
     *
     * @param filePath path of the file to be checked
     * @return
     */
    public static int getNumberOfPages(String filePath) {
        if (isPdf(filePath) == false) {
            return 0;
        }

        int numberofPages = 0;
        try {
            numberofPages = new PdfReader(filePath).getNumberOfPages();
        } catch (Exception ex) {
            LoggerManager.getLogger().log(Level.SEVERE, "File not found in selected path. Message = {0}", Toolkit.getStackTraceAsString(ex.getCause()));
        }
        return numberofPages;
    }
}
